//
//  OrderDetailsViewController.m
//  OMS
//
//  Created by goldeney on 14-9-28.
//  Copyright (c) 2014年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OMOrderDetailsViewController.h"
#import "AutoTextTableViewCell.h"
#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

#import "NSString+handle.h"
#import "NSKeyedArchiverUserLogin.h"

#import "Charts-Swift.h"
#import "PNChart.h"
#import "RKTabView.h"
#import "BGRadioView.h"

#import "JGActionSheet.h"
#import "WebServiceCommonRequest.h"

#import "EYInputPopupView.h"

#import "OMLogisticsInfoViewController.h"
#import "OMOrderDetailsViewCell.h"
#import "OMOrderRejectViewController.h"
#import "OMCreateOrderViewController.h"

@interface OMOrderDetailsViewController ()

@property (nonatomic,strong) NSMutableDictionary *orderInfo;
@property (nonatomic,strong) NSMutableArray *allSetArray;
@property (nonatomic,strong) NSMutableArray *titleSetArray;

@end

@implementation OMOrderDetailsViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"订单详情"];
        
    }
    return self;
}

- (void)createOrderSelector:(id)selector
{
    //复制下单
    OMCreateOrderViewController *viewController = [[OMCreateOrderViewController alloc] initWithValue:self.orderInfo];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)getPassingParameter:(id)object
{
    if(!object) return;
    self.orderInfo = [NSMutableDictionary dictionaryWithDictionary:object];
    
    BOOL isXD = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_DDGL_DDXD"].count;
    if(isXD){
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"复制下单" style:UIBarButtonItemStylePlain target:self action:@selector(createOrderSelector:)];
        [leftButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    
    //修改订单是否已读
    if([self.orderInfo objectFormatIntegerForKey:@"isRead"] < 1){
        NSString *orderID = [self.orderInfo objectFormatStringForKey:@"ID"];
        [self submitReadToNetWorkData:orderID];
    }
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getOrderAllOrders:self.orderInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getOrderAllOrders:(NSDictionary*)dic
{
    self.allSetArray = [NSMutableArray array];
    self.titleSetArray = [NSMutableArray array];
    
    //数据来源:3外部
    NSInteger SJLYint = [self.orderInfo objectFormatIntegerForKey:@"数据来源"];
    
    //外部订单需要显示合同信息，故添加合同信息
    if(SJLYint == 3){
        NSMutableArray *wOrderArray = [NSMutableArray array];
        [self.allSetArray addObject:wOrderArray];
        [self.titleSetArray addObject:[NSNumber numberWithInteger:-1]];
    }
    
    NSMutableArray *orderArray = [NSMutableArray array];
    [self addContractInfoKey:@"订单编号" toKey:@"订单编号：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    [self addContractInfoKey:@"合同名称" toKey:@"合同名称：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    [self addContractInfoKey:@"工程名称" toKey:@"工程名称：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    [self addContractInfoKey:@"施工部位" toKey:@"施工部位：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    //[self addContractInfoKey:@"制表人" toKey:@"下订单人：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    [self addContractInfoKey:@"制表时间" toKey:@"下单日期：" defaults:@"未知" format:nil form:dic toArray:orderArray];
    [self addContractInfoKey:@"备注" toKey:@"备        注：" defaults:@"无" format:nil form:dic toArray:orderArray];
    [self.allSetArray addObject:orderArray];
    [self.titleSetArray addObject:[NSNumber numberWithInteger:0]];
    
    NSMutableArray *concreteArray = [NSMutableArray array];
    [self addContractInfoKey:@"完整砼强度" toKey:@"强度等级：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"坍落度" toKey:@"坍  落  度：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"计划方量" toKey:@"计划方量：" defaults:@"未知" format:@"%@方" form:dic toArray:concreteArray];
    [self addContractInfoKey:@"浇筑方式" toKey:@"浇筑方式：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"原材料要求" toKey:@"原材料要求：" defaults:@"无" format:nil form:dic toArray:concreteArray];
    [self.allSetArray addObject:concreteArray];
    [self.titleSetArray addObject:[NSNumber numberWithInteger:1]];
    
    NSMutableArray *orderStateArray = [NSMutableArray array];
    [self addContractInfoKey:@"计划开盘时间" toKey:@"计划开盘时间：" defaults:@"未知" format:nil form:dic toArray:orderStateArray];
    [self addContractInfoKey:@"运输距离" toKey:@"运输距离：" defaults:@"未知" format:@"%@公里" form:dic toArray:orderStateArray];
    
    NSString *orderType = (SJLYint == 3) ? @"外部订单" :@"内部订单";
    [self addContractInfoKey:@"" toKey:@"订单类型：" defaults:orderType format:nil form:dic toArray:orderStateArray];
    
    [self addContractInfoKey:@"订单状态" toKey:@"订单状态：" defaults:@"未知" format:nil form:dic toArray:orderStateArray];
    //@订单状态（0未审核，1已审核,  2已拒绝）
    NSInteger DDZTint = [self.orderInfo objectFormatIntegerForKey:@"DDZT"];
    if (DDZTint == 2)
    [self addContractInfoKey:@"拒绝原因" toKey:@"拒绝原因：" defaults:@"无" format:nil form:dic toArray:orderStateArray];
    //------------------//
    [self.allSetArray addObject:orderStateArray];
    [self.titleSetArray addObject:[NSNumber numberWithInteger:2]];
    
    //外部来源数据未接收、未分发站点，不显示站点信息
    if(DDZTint == 0 || DDZTint == 1){
        NSMutableArray *distributeArray = [NSMutableArray array];
        [self addContractInfoKey:@"分发状态" toKey:@"分发状态：" defaults:@"未知" format:nil form:dic toArray:distributeArray];
        [self addContractInfoKey:@"原始分发站" toKey:@"原始分发站：" defaults:@"未知" format:nil form:dic toArray:distributeArray];
        [self addContractInfoKey:@"实际分发站" toKey:@"实际分发站：" defaults:@"未知" format:nil form:dic toArray:distributeArray];
        [self addContractInfoKey:@"是否驳回" toKey:@"是否存在驳回：" defaults:@"未知" format:nil form:dic toArray:distributeArray];
        [self.allSetArray addObject:distributeArray];
        [self.titleSetArray addObject:[NSNumber numberWithInteger:3]];
    }
    
    NSMutableArray *constructionArray = [NSMutableArray array];
    [self addContractInfoKey:@"工地联系人" toKey:@"工地联系人：" defaults:@"未知" format:nil form:dic toArray:constructionArray];
    [self addContractInfoKey:@"工地联系电话" toKey:@"工地联系电话：" defaults:@"未知" format:nil form:dic toArray:constructionArray];
    [self addContractInfoKey:@"工地地址" toKey:@"工地地址：" defaults:@"未知" format:nil form:dic toArray:constructionArray];
    [self.allSetArray addObject:constructionArray];
    [self.titleSetArray addObject:[NSNumber numberWithInteger:4]];
    
}

#pragma mark - 合同进度分析图

- (void)drawContractPlanChart:(UITableViewCell *)cell
{
    NSString *htmc = [self.orderInfo objectFormatStringForKey:@"合同名称"];
    NSNumber *qld = [self.orderInfo objectFormatFloatNumberForKey:@"签订方量"];
    NSNumber *zjl = [self.orderInfo objectFormatFloatNumberForKey:@"追加方量"];
    NSNumber *htzl = [self.orderInfo objectFormatFloatNumberForKey:@"合同总量"];
    NSNumber *ywcl = [self.orderInfo objectFormatFloatNumberForKey:@"已完成量"];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SuperWidth - 20, 22)];
    titleLable.text = htmc;
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    UILabel *titleLable2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 28, SuperWidth - 20, 22)];
    titleLable2.text = [NSString stringWithFormat:@"签订量:%@方  追加量:%@方",qld,zjl];
    titleLable2.font = [UIFont systemFontOfSize:11];
    titleLable2.textAlignment = NSTextAlignmentCenter;
    titleLable2.textColor = [UIColor grayColor];
    [cell.contentView addSubview:titleLable2];
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 40, SuperWidth, 240)];
    _chartView.usePercentValuesEnabled = YES;
//    _chartView.holeTransparent = YES;
    //_chartView.centerTextFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:12.f];
    _chartView.holeRadiusPercent = 0.42f;
    _chartView.transparentCircleRadiusPercent = 0.46f;
//    _chartView.descriptionText = @"";
    _chartView.drawCenterTextEnabled = YES;
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.f;
    _chartView.rotationEnabled = YES;
    _chartView.userInteractionEnabled = NO;
    _chartView.centerText = [NSString stringWithFormat:@"合同总量\n%@m³\n%@m³\n已完成量",htzl,ywcl];;
    
    ChartLegend *l = _chartView.legend;
//    l.position = ChartLegendPositionRightOfChart;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.xEntrySpace = 10.f;
    l.yEntrySpace = 5.f;
    
    _chartView.data = [self setDataArray:self.orderInfo];
    [_chartView highlightValues:nil];
    [_chartView animateWithXAxisDuration:1.5 yAxisDuration:1.5 easingOption:ChartEasingOptionEaseOutBack];
    [cell.contentView addSubview:_chartView];
    
    //提示
    UILabel *titleLable3 = [[UILabel alloc] initWithFrame:CGRectMake(10, 270, SuperWidth - 20, 22)];
    titleLable3.text = @"温馨提示：接收外部订单时，请仔细核对相关信息";
    titleLable3.font = [UIFont systemFontOfSize:12];
    titleLable3.textAlignment = NSTextAlignmentCenter;
    titleLable3.textColor = [UIColor grayColor];
    [cell.contentView addSubview:titleLable3];
}

- (PieChartData*)setDataArray:(NSDictionary*)dictionary
{
    CGFloat htzl = [[dictionary objectFormatFloatNumberForKey:@"合同总量"] floatValue];
    CGFloat ywcl = [[dictionary objectFormatFloatNumberForKey:@"已完成量"] floatValue];
    
    htzl = (htzl <= 0 ) ? 1 : htzl;
    CGFloat syl = htzl - ywcl;
    
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:(ywcl/htzl*100) label:@"完成量"]];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:(syl/htzl*100) label:@"剩余量"]];
    
    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    [xVals addObject:@"完成量"];
    [xVals addObject:@"剩余量"];
    
    NSString *htzt = [NSString stringWithFormat:@"合同情况"];
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:htzt];
    dataSet.sliceSpace = 2.0;
    //dataSet.iconsOffset = CGPointMake(0, 40);
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorLigthBlue];
    [colors addObject:ThemeColorGreen];
    dataSet.colors = colors;
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" %";
    //[data setValueFormatter:pFormatter];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    return data;
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allSetArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    BOOL isSH = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_DDGL_DDSH"].count;
    BOOL isJD = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_DDGL_DDJD"].count;
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSInteger userID = userInfo.Id.integerValue;
    NSInteger orderID = [self.orderInfo objectFormatIntegerForKey:@"制表人"];
    
    //订单信息 @订单状态（0未审核，1已审核,  2已拒绝, 3未接收，4未接单）
    //@分发状态（0未分发，1已分发）
    //@驳回状态（0未驳回，1已驳回）
    NSInteger functionNumber = [[self.titleSetArray objectAtIndex:section] integerValue];
    NSInteger DDZTint = [self.orderInfo objectFormatIntegerForKey:@"DDZT"];
    NSInteger FFZTint = [self.orderInfo objectFormatIntegerForKey:@"FFZT"];
    NSInteger BHZTint = [self.orderInfo objectFormatIntegerForKey:@"BHZT"];
    if (functionNumber == -1 && DDZTint == 4 && isJD) return 2;
    if (functionNumber == 0 && DDZTint == 0&& isSH) return 2;
    if (functionNumber == 1 && userID == orderID && DDZTint == 0) return 2;
    if (functionNumber == 2 && FFZTint >= 1 && DDZTint == 1) return 2;//存在发货消息
    if (functionNumber == 3 && DDZTint != 2 && BHZTint >= 1 ) return 2;//分发信息
    if (functionNumber == 4 && DDZTint != 2) return 2;//联系电话
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = [self.allSetArray objectAtIndex:indexPath.section];
    NSInteger functionNumber = [[self.titleSetArray objectAtIndex:indexPath.section] integerValue];
    //NSInteger DDZTint = [self.orderInfo objectFormatIntegerForKey:@"DDZT"];
    
    if (functionNumber == -1 && indexPath.row == 0){
        UITableViewCell *cell = cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableSampleIdentifier2"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self drawContractPlanChart:cell];
        return cell;
    }
    
    //接单和新增操作
    if (functionNumber == -1 && indexPath.row == 1){
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier1";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *tabItems = [NSMutableArray array];//选项卡
        
        RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_favorite_highlighted"]];
        tabItem1.titleString = @"立即接单";
        tabItem1.titleFont = [UIFont systemFontOfSize:12];
        [tabItem1 addTarget:self selector:@selector(distributeSelector:)];
        [tabItems addObject:tabItem1];
        
        RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_add_background_highlighted"]];
        tabItem2.titleString = @"复制下单";
        tabItem2.titleFont = [UIFont systemFontOfSize:12];
        [tabItem2 addTarget:self selector:@selector(createOrderSelector:)];
        [tabItems addObject:tabItem2];
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
    
    //审核和新增操作
    if (functionNumber == 0 && indexPath.row == 1){
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier1";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *tabItems = [NSMutableArray array];//选项卡
        
        RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"navigationbar_compose_highlighted"]];
        tabItem1.titleString = @"通过审核";
        tabItem1.titleFont = [UIFont systemFontOfSize:12];
        [tabItem1 addTarget:self selector:@selector(auditOrderSelector:)];
        [tabItems addObject:tabItem1];
        
        RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_keyboard_background_highlighted"]];
        tabItem2.titleString = @"拒绝本单";
        tabItem2.titleFont = [UIFont systemFontOfSize:12];
        [tabItem2 addTarget:self selector:@selector(refuseSelector:)];
        [tabItems addObject:tabItem2];
        
        RKTabItem *tabItem3 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_stop_highlighted"]];
        tabItem3.titleString = @"作废本单";
        tabItem3.titleFont = [UIFont systemFontOfSize:12];
        [tabItem3 addTarget:self selector:@selector(deleteSelector:)];
        [tabItems addObject:tabItem3];
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
    
    //修改订单
    if (functionNumber == 1 && indexPath.row == 1){
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier2";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *tabItems = [NSMutableArray array];//选项卡
        
        RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"navigationbar_compose_highlighted"]];
        tabItem1.titleString = @"修改订单";
        tabItem1.titleFont = [UIFont systemFontOfSize:12];
        [tabItem1 addTarget:self selector:@selector(modifyOrderSelector:)];
        [tabItems addObject:tabItem1];
        
        RKTabItem *tabItem3 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_stop_highlighted"]];
        tabItem3.titleString = @"作废订单";
        tabItem3.titleFont = [UIFont systemFontOfSize:12];
        [tabItem3 addTarget:self selector:@selector(deleteSelector:)];
        [tabItems addObject:tabItem3];
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
    
    if (functionNumber == 2 && indexPath.row == 1) {
        //发货信息
        OMOrderDetailsViewCell *cell = [[OMOrderDetailsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OMOrderDetailsViewCell"];
        cell.titleLabel.text = @"罐车发货信息";
        cell.iconImageView.image = [UIImage imageNamed:@"hotel_location_big"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = [UIColor colorWithRed:254/255.0 green:247/255.0 blue:246/255.0 alpha:1];
        
//        if(DDZTint == 1) cell.subheadLabel.text = @"订单已审核，正在发货中";
//        else cell.subheadLabel.text = @"订单正在审核，等待发货中";
        
        NSInteger fffl = [self.orderInfo objectFormatIntegerForKey:@"发货方量"];
        NSInteger ffcc = [self.orderInfo objectFormatIntegerForKey:@"发货车次"];
        if(ffcc>0) cell.subheadLabel.text = [NSString stringWithFormat:@"累计发货%ld方，已发%ld车",fffl,ffcc];
        else cell.subheadLabel.text = @"正等待发货";
        
        return cell;
    }
    
    if (functionNumber == 3 && indexPath.row == 1) {
        //驳回信息
        OMOrderDetailsViewCell *cell = [[OMOrderDetailsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OMOrderDetailsViewCell"];
        cell.titleLabel.text = @"订单驳回明细";
        cell.iconImageView.image = [UIImage imageNamed:@"hotel_location_big"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = [UIColor colorWithRed:254/255.0 green:247/255.0 blue:246/255.0 alpha:1];
        cell.subheadLabel.text = [self.orderInfo objectFormatStringForKey:@"驳回次数" format:@"该订单被驳回了%@次" defaults:@"无法获取驳回次数"];
        return cell;
    }
    
    if (functionNumber == 4 && indexPath.row == 1) {
        //分发信息
        OMOrderDetailsViewCell *cell = [[OMOrderDetailsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OMOrderDetailsViewCell"];
        cell.subheadLabel.text = [self.orderInfo objectFormatStringForKey:@"工地联系电话" defaults:@"无号码"];
        //cell.subheadLabel.font = [UIFont systemFontOfSize:13];
        cell.explainLabel.text = @"拨打";
        cell.iconImageView.image = [UIImage imageNamed:@"group_buy_telephone"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = [UIColor colorWithRed:254/255.0 green:247/255.0 blue:246/255.0 alpha:1];
        cell.titleLabel.text = [self.orderInfo objectFormatStringForKey:@"工地联系人" defaults:@"无联系人"];;
        return cell;
    }
    
    //通用页面
    NSString *identifier = [NSString stringWithFormat:@"OrderInfoTableViewCell%ld",(long)indexPath.section];
    AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    [cell setDataArray:array];
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    //lable.textColor = [UIColor colorWithRed:31/255.00 green:161/255.00 blue:211/255.00 alpha:1.0];
    lable.textColor = ThemeColorBlue;
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    NSInteger functionNumber = [[self.titleSetArray objectAtIndex:section] integerValue];
    if (functionNumber == -1) {
        lable.text = @"外部订单关联合同";
    } else if (functionNumber == 0) {
        lable.text = @"订单基本信息";
    } else if(functionNumber == 1){
        lable.text = @"混凝土信息";
    } else if(functionNumber == 2){
        lable.text = @"订单状态";
    } else if(functionNumber == 3){
        lable.text = @"分发信息";
    } else if(functionNumber == 4){
        lable.text = @"工地信息";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = [self.allSetArray objectAtIndex:indexPath.section];
    NSInteger functionNumber = [[self.titleSetArray objectAtIndex:indexPath.section] integerValue];
    
    //合同信息
    if (functionNumber == -1 && indexPath.row == 0) {
        return 300;
    }
    
    if (functionNumber == 0 && indexPath.row == 1)
        return 48;
    
    if (functionNumber == -1 && indexPath.row == 1)
        return 48;
    
    //修改订单
    if (functionNumber == 1 && indexPath.row == 1) {
        return 46;
    }
    
    //发货信息
    if (functionNumber == 2 && indexPath.row == 1) {
        return 46;
    }
    
    //分发信息
    if (functionNumber == 3 && indexPath.row == 1) {
        return 46;
    }
    
    //拨打电话
    if (functionNumber == 4 && indexPath.row == 1) {
        return 46;
    }
    
    //通用返回
    AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
    [cell setDataArray:array];
    return cell.contentView.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //物流信息
    NSInteger functionNumber = [[self.titleSetArray objectAtIndex:indexPath.section] integerValue];
    if(functionNumber == 2 && indexPath.row == 1){
        //罐车发货
        OMLogisticsInfoViewController *viewController = [[OMLogisticsInfoViewController alloc] initWithValue:self.orderInfo];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if(functionNumber == 3 && indexPath.row == 1){
        //驳回信息
        OMOrderRejectViewController *viewController = [[OMOrderRejectViewController alloc] initWithValue:self.orderInfo];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if(functionNumber == 4 && indexPath.row == 1){
        //拨打电话
        [self callAction:self.orderInfo];
    }
    
}

- (void)callAction:(NSDictionary *)orderInfo
{
    NSString *phoneNo = [self.orderInfo objectFormatStringForKey:@"工地联系电话"];
    
    //获取电话号码
    NSMutableString *phoneNumber = [[NSMutableString alloc] init];
    [phoneNumber appendString:@"tel://"];
    
    NSString *mobliePhone = phoneNo;
    if (mobliePhone && ![mobliePhone isEqualToString:@""]){//拨打移动号码
        [phoneNumber appendString:mobliePhone];
        
    } else {
        //未找到手机号码
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有工地联系人电话，无法拨打！" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

#pragma mark -
#pragma mark 网络获取订单分发站点

- (void)distributeStionNetWorkContractData
{
    JGProgressHUD *HUD = [self showSimpleHUDText:@"获取站点中"];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_JDZX_GETSITE"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self distributeActionSheetStionHandle:firstArray];
        } else {
            [self showErrorHUDText:@"无站点"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"获取失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

//接单弹出框
- (void)distributeActionSheetStionHandle:(NSArray*)stationArray
{
    NSMutableArray *sortByItemsArray = [[NSMutableArray alloc] init];
    for(int i=0;i<stationArray.count;i++){
        NSDictionary *mDictionary = [stationArray objectAtIndex:i];
        [sortByItemsArray addObject:[mDictionary objectFormatStringForKey:@"U_Name"]];
    }
    
    CGFloat height = sortByItemsArray.count * 44;
    BGRadioView *radioViewSortBy = [[BGRadioView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth - 40, height)];
    radioViewSortBy.rowItems =  sortByItemsArray;
    radioViewSortBy.maxRow = [sortByItemsArray count];
    radioViewSortBy.isMultiSelect = NO;
    
    JGActionSheetSection *sheetSection = [JGActionSheetSection sectionWithTitle:@"接单" message:@"提示：接单成功后，订单将会等待审核，请根据订单信息指定生产站点。请选择站点：" buttonTitles:@[@"提交"] buttonStyle:JGActionSheetButtonStyleDefault contentView:radioViewSortBy];
    [sheetSection setButtonStyle:JGActionSheetButtonStyleRed forButtonAtIndex:0];
    
    JGActionSheetSection *sheetSectionCancel = [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel];
    
    JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[sheetSection, sheetSectionCancel]];
    [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
        //接单
        if (indexPath.section == 0) {
            NSDictionary *mDictionary = [stationArray objectAtIndex:radioViewSortBy.optionNo];
            NSString *StationID = [mDictionary objectFormatStringForKey:@"Code"];
            NSString *station = [mDictionary objectFormatStringForKey:@"U_Name"];
            [self distributeNetWorkContractData:StationID station:station];
        }
        [sheet dismissAnimated:YES];
    }];
    [simple showInView:self.navigationController.view animated:YES];
    
}

//网络接单处理
- (void)distributeNetWorkContractData:(NSString*)stationID station:(NSString*)station
{
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在处理"];
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_JDZX_ADD"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"Id" value:orderId];
    [content addParameterKey:@"UserId" value:userInfo.Id];
    [content addParameterKey:@"Note" value:@""];
    [content addParameterKey:@"FFZD" value:stationID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"接单成功"];
            
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            [self.orderInfo setValue:@0 forKey:@"DDZT"];
            [self.orderInfo setValue:@"未审核" forKey:@"订单状态"];
            [self.orderInfo setValue:station forKey:@"原始分发站"];
            [self.orderInfo setValue:station forKey:@"实际分发站"];
            
            [self getOrderAllOrders:self.orderInfo];
            [self.tableView reloadData];
            
            NSArray *resultArray = @[originalDic,self.orderInfo];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReceiveOrder" dataValue:resultArray];
        } else {
            [self showErrorHUDText:@"接单失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"接单失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

#pragma mark -
#pragma mark 网络获取订单审核分发站点

- (void)auditOrderStionNetWorkContractData
{
    JGProgressHUD *HUD = [self showSimpleHUDText:@"获取站点中"];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_JDZX_GETSITE"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self auditOrderActionSheetStionHandle:firstArray];
        } else {
            [self showErrorHUDText:@"无站点"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"获取失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

//接单弹出框
- (void)auditOrderActionSheetStionHandle:(NSArray*)stationArray
{
    NSInteger selectStation = -1;
    NSMutableArray *sortByItemsArray = [[NSMutableArray alloc] init];
    for(int i=0;i<stationArray.count;i++){
        NSDictionary *mDictionary = [stationArray objectAtIndex:i];
        NSString *U_Name = [mDictionary objectFormatStringForKey:@"U_Name"];
        
        NSString *ysffStation = [self.orderInfo objectFormatStringForKey:@"实际分发站"];
        if([U_Name isEqualToString:ysffStation]){
            selectStation = i;
            U_Name = [NSString stringWithFormat:@"%@  <--默认分发站",U_Name];
            [sortByItemsArray addObject:U_Name];
        } else {
            [sortByItemsArray addObject:U_Name];
        }
    }
    
    CGFloat height = sortByItemsArray.count * 44;
    BGRadioView *radioViewSortBy = [[BGRadioView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth - 40, height)];
    radioViewSortBy.rowItems =  sortByItemsArray;
    radioViewSortBy.maxRow = [sortByItemsArray count];
    radioViewSortBy.isMultiSelect = NO;
    radioViewSortBy.optionNo = selectStation;
    
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"实际分发站" defaults:@"未选择"];
    NSString *message = [NSString stringWithFormat:@"提示：订单审核通过后，系统会自动分发到指定站点生产。如需修改生产站点，请重新选择站点：\n ***该订单默认分发站：%@***",orderId];
    
    JGActionSheetSection *sheetSection = [JGActionSheetSection sectionWithTitle:@"订单审核" message:message buttonTitles:@[@"通过审核"] buttonStyle:JGActionSheetButtonStyleDefault contentView:radioViewSortBy];
    [sheetSection setButtonStyle:JGActionSheetButtonStyleRed forButtonAtIndex:0];
    
    JGActionSheetSection *sheetSectionCancel = [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel];
    
    JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[sheetSection, sheetSectionCancel]];
    [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
        if (indexPath.section == 0) {
            NSDictionary *mDictionary = [stationArray objectAtIndex:radioViewSortBy.optionNo];
            NSString *StationID = [mDictionary objectFormatStringForKey:@"Code"];
            NSString *station = [mDictionary objectFormatStringForKey:@"U_Name"];
            [self auditOrderNetWorkContractData:StationID station:station];
        }
        [sheet dismissAnimated:YES];
    }];
    [simple showInView:self.navigationController.view animated:YES];
    
}

//网络审核订单
- (void)auditOrderNetWorkContractData:(NSString*)stationID station:(NSString*)station
{
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在处理"];
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_DDSH"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"订单ID" value:orderId];
    [content addParameterKey:@"审核人" value:userInfo.username];
    [content addParameterKey:@"实际分发站" value:stationID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"审核成功"];
            
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            [self.orderInfo setValue:@1 forKey:@"DDZT"];
            [self.orderInfo setValue:@"已审核" forKey:@"订单状态"];
            [self.orderInfo setValue:station forKey:@"实际分发站"];
            
            [self getOrderAllOrders:self.orderInfo];
            [self.tableView reloadData];
            
            NSArray *resultArray = @[originalDic,self.orderInfo];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReceiveOrder" dataValue:resultArray];
        } else {
            [self showErrorHUDText:@"审核失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"审核失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

#pragma mark -
#pragma mark 拒绝订单

//拒绝订单
- (void)refuseSelector:(id)sender
{
    [EYInputPopupView popViewWithTitle:@"订单拒绝" contentText:@"请输入拒绝原因" cancelButton:@"取消"
                              okButton:@"拒绝" type:EYInputPopupView_Type_multi_line
                           cancelBlock:^{
                               NSLog(@"left button cancel clicked");
                           } confirmBlock:^(UIView *view, NSString *text) {
                               //类型 1、通过  2、拒绝
                               NSLog(@"left button confirmBlock clicked");
                               [self applyOrderExamineReason:text];
                           } dismissBlock:^{
                               NSLog(@"left button dismiss clicked");
                           }];
}

//审核提交
- (void)applyOrderExamineReason:(NSString*)reason
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setShowLoadingPrompt:self.navigationController labelText:@"正在处理"];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_DDJJ"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"订单ID" value:orderId];
    [content addParameterKey:@"审核人" value:userInfo.username];
    [content addParameterKey:@"原因" value:reason];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0){
            firstArray = [result.resultArray firstObject];
        }
        //数据处理及显示
        [self verificationResultHandle:firstArray reason:reason];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"拒绝订单失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"网络未连接"];
    }];
}

- (void)verificationResultHandle:(NSArray*)results reason:(NSString*)reason
{
    if (results && results.count>0) {
        //提交成功
        [self showSuccessHUDText:@"拒绝订单成功"];
        NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
        [self.orderInfo setValue:@2 forKey:@"DDZT"];
        [self.orderInfo setValue:@"已拒绝" forKey:@"订单状态"];
        [self.orderInfo setValue:reason forKey:@"拒绝原因"];
        
        [self getOrderAllOrders:self.orderInfo];
        [self.tableView reloadData];
        
        NSArray *resultArray = @[originalDic,self.orderInfo];
        if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReceiveOrder" dataValue:resultArray];
        
    } else {
        //网络不畅
        [self showErrorHUDText:@"拒绝订单失败"];
    }
}

#pragma mark -
#pragma mark Button Event

//修改订单
- (void)modifyOrderSelector:(id)sender
{
    OMCreateOrderViewController *viewController = [[OMCreateOrderViewController alloc] initWithModifyValue:self.orderInfo];
    [self.navigationController pushViewController:viewController animated:YES];
}

//订单作废
- (void)deleteSelector:(id)sender
{
    [EYInputPopupView popViewWithTitle:@"订单作废" contentText:@"请输入作废原因" cancelButton:@"取消"
                              okButton:@"作废" type:EYInputPopupView_Type_multi_line
                           cancelBlock:^{
                               NSLog(@"left button cancel clicked");
                           } confirmBlock:^(UIView *view, NSString *text) {
                               NSLog(@"left button confirmBlock clicked");
                               [self deleteNetWorkContractData:text];
                           } dismissBlock:^{
                               NSLog(@"left button dismiss clicked");
                           }];
}

//网络订单作废
- (void)deleteNetWorkContractData:(NSString*)reason
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *orderId = [self.orderInfo objectFormatStringForKey:@"ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setShowLoadingPrompt:self.navigationController labelText:@"正在处理"];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_DDZF"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"订单ID" value:orderId];
    [content addParameterKey:@"审核人" value:userInfo.username];
    [content addParameterKey:@"原因" value:reason];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0){
            firstArray = [result.resultArray firstObject];
        }
        //数据处理及显示
        [self verificationdeleteResultHandle:firstArray reason:reason];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"作废订单失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"网络未连接"];
    }];
}

- (void)verificationdeleteResultHandle:(NSArray*)results reason:(NSString*)reason
{
    if (results && results.count>0) {
        //提交成功
        [self showSuccessHUDText:@"作废订单成功"];
        NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
        [self.orderInfo setValue:@3 forKey:@"DDZT"];
        [self.orderInfo setValue:@"已作废" forKey:@"订单状态"];
        [self.orderInfo setValue:reason forKey:@"拒绝原因"];
        
        [self getOrderAllOrders:self.orderInfo];
        [self.tableView reloadData];
        
        NSArray *resultArray = @[originalDic,self.orderInfo];
        if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReceiveOrder" dataValue:resultArray];
        
    } else {
        //网络不畅
        [self showErrorHUDText:@"作废订单失败"];
    }
}

#pragma mark -
#pragma mark Button Event

//接单
- (void)distributeSelector:(id)sender
{
    BOOL isXD = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_DDGL_DDJD"].count;
    if(isXD) [self distributeStionNetWorkContractData];
    else [self showErrorHUDText:@"无权限接单"];
}

//订单审核
- (void)auditOrderSelector:(id)sender
{
    [self auditOrderStionNetWorkContractData];
}

#pragma mark 提交订单变更

- (void)submitReadToNetWorkData:(NSString*)orderID
{
    //@审核状态（0未审核，1已审核, 2已拒绝）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_READ"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        if(firstArray && firstArray.count>0){
            NSLog(@"订单阅读状态提交成功");
            
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            [self.orderInfo setValue:@1 forKey:@"isRead"];
            
            NSDictionary *originalDic1 = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            NSArray *resultArray = @[originalDic,originalDic1];
            
            if(self.backResultDelagate)
            [self.backResultDelagate backResultDataKey:self.key dataValue:resultArray];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===订单阅读状态==%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===订单阅读状态==%@",error);
    }];
    
}

#pragma mark 获取修改订单

- (void)getModifyOrderToNetWorkData:(NSString*)orderID
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_LIST_DETAIL"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            NSMutableDictionary *originalDic1 = [NSMutableDictionary dictionaryWithDictionary:firstArray.firstObject];
            NSArray *resultArray = @[self.orderInfo,originalDic1];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:self.key dataValue:resultArray];
            
            self.orderInfo = originalDic1;
            [self getOrderAllOrders:originalDic1];
            [self.tableView reloadData];
        } else {
            NSLog(@"===未找到订单===");
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReloadOrder" dataValue:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===获取修改订单失败==%@",error);
        if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReloadOrder" dataValue:nil];
        [self.navigationController popViewControllerAnimated:YES];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===获取修改订单失败==%@",error);
        if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"ReloadOrder" dataValue:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

#pragma mark
#pragma mark - BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if([key isEqualToString:@"ModifyOrder"]){//修改订单
        NSString *orderID = [self.orderInfo objectFormatStringForKey:@"ID"];
        [self getModifyOrderToNetWorkData:orderID];
    }
}

@end
